package com.example.studentalarm.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;

import java.util.ArrayList;

/***
 * 权限管理
 */
public class PermissionManage {
    public static final int SDK_PERMISSION_REQUEST = 127;
    private Context context;
    private String[] permissionArray;//默认权限 读写、读取电话、相册

    public PermissionManage(Builder builder) {
        this.context = builder.mContext;
        this.permissionArray = builder.permission == null ? new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.READ_PHONE_STATE, Manifest.permission.CAMERA} : builder.permission;
    }


    public void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<>();
            //读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
            for (String permission : permissionArray) {
                addPermission(permissions, permission);
            }
            if (permissions.size() > 0) {
                ActivityCompat.requestPermissions(((Activity) context), permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);

            }
        }
    }

    /****
     * 添加权限
     * @param permissionsList
     * @param permission
     * @return
     */
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (context.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
                if (((Activity) context).shouldShowRequestPermissionRationale(permission)) {
                    return true;
                } else {
                    permissionsList.add(permission);
                    return false;
                }
            } else {
                return true;
            }
        }
        return false;
    }


    public static class Builder {
        private Context mContext;
        private String[] permission;

        public Builder(Context mContext) {
            this.mContext = mContext;
        }

        public Builder setPermission(String[] permission) {
            this.permission = permission;
            return this;
        }


        public PermissionManage builder() {
            return new PermissionManage(this);

        }


    }

}
